import React, { Component, Fragment } from "react";
// antd
import { Dropdown, Menu, Button, Col, Pagination, Form, Input, Tag, Select, Table, Space, notification, Typography, Modal, message} from "antd";
import {CopyToClipboard} from 'react-copy-to-clipboard';
import { CopyOutlined, CheckOutlined, DownOutlined } from '@ant-design/icons';
import Action from "@c/buttonAction/Index";


// http
import http from '../../../utils/request';
const { Option } = Select;
const { Text } = Typography;

class CloudRamUser extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "用户ID/名称", dataIndex: "user_id", key: "user_id",
                    render: (text, rowData) => {
                        return(
                            <Space direction="vertical">
                                <CopyToClipboard text={rowData.user_id} 
                                    onCopy={() => 
                                        this.setState({copied: true},
                                        notification.open({
                                            message: '已复制到剪贴板',
                                            icon: <CheckOutlined style={{ color: 'green' }} />,
                                            duration: 2,
                                            placement: 'top',
                                        })
                                    )}
                                >
                                    <span><span style={{marginRight: "5px"}}><CopyOutlined /></span><span style={{color: "#6587FF"}}>{rowData.user_id}</span></span>
                                </CopyToClipboard>
                                 
                                <Text >{rowData.user_name}</Text>
                            </Space>
                        )
                    }
                },
                {title: "登录名", dataIndex: "login_name", key: "login_name", width: "300px",
                    render: (text, rowData) => {
                        return(
                            <div>
                                {rowData.login_name}
                            </div>
                        )
                    }
                },
                {title: "云平台", dataIndex: "cloud-platform", key: "cloud-platform",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.platform}-{rowData.account_name}</Tag>
                            </div>
                        )
                    }
                },
                {title: "创建类型", dataIndex: "provision_type", key: "provision_type",
                    render: (text, rowData) => {
                        return (
                            <Tag color="blue">{rowData.provision_type}</Tag>
                        )
                    }
                },
                {title: "最后登录", dataIndex: "last_login_date", key: "last_login_date"},
                {title: "手机", dataIndex: "mobile", key: "mobile"},
                {title: "邮箱", dataIndex: "email", key: "email"},
                {title: "备注", dataIndex: "comment", key: "comment"}
            ],
            loading: false,
            search_user_id: null,
            search_login_name: null,
            search_account_name: null,
            search_platform: null,
            search_provision_type: null,
            search_last_login_date: null,
            search_option_account: [],
            search_option_platform: [],
            search_option_username: [],
            visible_add: false, // 用于控制添加弹窗显示
            visible_del: false, // 用于控制删除弹窗显示
        }
        this.formRefAdd = React.createRef()
        this.formRefDel = React.createRef()
    }

    componentDidMount() {
        this.loadData()
        this.loadDataPlatform()
    }

    loadDataPlatform = () => {
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/cloud/platform', {params: requestData}).then(response=>{
            const search_option_platform = []
            const resp_data = response.data.data.items
            for (let i = 0; i < resp_data.length; i++) {
                search_option_platform.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            this.setState({
                search_option_platform: search_option_platform
            })
        })
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'user_id__contains': this.state.search_user_id,
            'login_name__contains': this.state.search_login_name,
            'platform': this.state.search_platform,
            'account_name': this.state.search_account_name,
            'provision_type': this.state.search_provision_type,
            'last_login_date': this.state.search_last_login_date
        }

        // 获取分组列表
        http.get('/cloud/ram/user', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    /** 添加OPENAPI用户按钮 */
    onAddUserBtn = () => {
        this.setState({
            visible_add: true
        })
    }

    /** 添加OPENAPI用户取消 */
    onFinishAddCancel = () => {
        this.setState({
            visible_add: false
        })
        this.formRefAdd.current.resetFields()
    }

    /** 添加OPENAPI用户提交 */
    onFinishAdd = (data) => {
        const requestData = {
            username: data.username,
            comments: data.comments,
            platform: data.platform,
            account_name: data.account_name,
        }
        console.log('Policy Document:', requestData);
        http.post('/cloud/ramnew/user', requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_add: false,
            })
            this.formRefAdd.current.resetFields()
            this.loadData()
        }).catch()
    }

    /** 删除OPENAPI用户按钮 */
    onDelUserBtn = () => {
        this.setState({
            visible_del: true
        })
    }

    /** 删除OPENAPI用户取消 */
    onFinishDelCancel = () => {
        this.setState({
            visible_del: false
        })
        this.formRefDel.current.resetFields()
    }


    /** 删除OPENAPI用户提交 */
    onFinishDel = (data) => {
        const requestData = {
            username: data.username,
            ak: data.ak,
            platform: data.platform,
            account_name: data.account_name,
        }
        console.log('Policy Document:', requestData);
        http.delete('/cloud/ramnew/user', { data: requestData }).then(response => {
            message.success(response.data.msg);
            this.setState({
                visible_del: false,
            });
            this.loadData();
        }).catch()
    }


    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 云平台搜索 */
    onFinishSearch = (data) => {
        this.setState({
            page: 1,
            search_user_id: data.user_id ? data.user_id : null,
            search_login_name: data.login_name ? data.login_name : null,
            search_account_name: data.account_name ? data.account_name : null,
            search_platform: data.platform ? data.platform : null,
            search_provision_type: data.provision_type,
            search_last_login_date: data.last_login_date
        })
        this.loadData()
    }

    // 搜索切换云平台
    onChangePlatform = (value) => {
        if (value) {
            this.setState({
                search_instance_platform: value
            })

            const requestData = {
                'page': 1,
                'limit': 1000,
                'platform': value
            }
    
            http.get('/cloud/account', {params: requestData}).then(response=>{
                const search_option_account = []
                const resp_data = response.data.data.items
                for (let i = 0; i < resp_data.length; i++) {
                    search_option_account.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
                }
                this.setState({
                    search_option_account: search_option_account
                })
            })

        } else {
            this.setState({
                search_option_account: '',
            })
        }
    }

    // 搜索切换账户
    onChangeAccount = (value) => {
        const platform = this.formRefDel.current.getFieldValue('platform');

        if (value) {
            this.setState({
                search_instance_account_name: value
            })

            const requestData = {
                'page': 1,
                'limit': 1000,
                'account_name': value,
                'platform': platform
            }
    
            http.get('/cloud/ram/user', {params: requestData}).then(response=>{
                const search_option_username = []
                const resp_data = response.data.data.items
                for (let i = 0; i < resp_data.length; i++) {
                    search_option_username.push(<Option key={resp_data[i].login_name}>{resp_data[i].login_name}</Option>)
                }
                this.setState({
                    search_option_username: search_option_username
                })
            })

        } else {
            this.setState({
                search_option_username: '',
            })
        }
    }

    // 搜索云账户
    onChangeAccountName = (value) => {
        this.setState({
            search_account_name: value ? value : null
        })
    }

    render(){
        const { loading, dataSource, columns, page, total, search_option_platform, search_option_account, search_option_username, visible_add, visible_del } = this.state
        const operations = (
            <Menu
                items={[
                    {
                        label: (
                            <Action.Button onClick={() => this.onAddUserBtn()}>添加OPENAPI用户</Action.Button>
                        ),
                        key: '0',
                    },
                    {
                        label: (
                            <Action.Button onClick={() => this.onDelUserBtn()}>删除OPENAPI用户</Action.Button>
                        ),
                        key: '1',
                    }
                ]}
            />
        );
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        return (
            <Fragment>

                <Form layout="inline" onFinish={this.onFinishSearch} size="small">
                    <Form.Item label="云平台" name="platform">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择区域"
                            optionFilterProp="children"
                            onChange={this.onChangePlatform}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {search_option_platform}
                        </Select>
                    </Form.Item>

                    <Form.Item label="云账户" name="account_name">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择云账户"
                            onChange={this.onChangeAccountName}
                            >
                            {search_option_account}
                        </Select>                      
                    </Form.Item>

                    <Form.Item label="创建类型" name="provision_type">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="用户创建类型"
                            >
                            <Option key="Manual">手动创建</Option>
                            <Option key="SCIM">SCIM协议同步创建</Option>
                            <Option key="CloudSSO">云SSO同步创建</Option>
                        </Select>  
                    </Form.Item>

                    <Form.Item label="最后登录" name="last_login_date">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="最后登录时间"
                            >
                            <Option key="从未登录过">从未登录过</Option>
                        </Select>  
                    </Form.Item>

                    <Form.Item label="用户ID" name="user_id">
                        <Input placeholder="请输入UserID"  />
                    </Form.Item>

                    <Form.Item label="登录名" name="login_name">
                        <Input placeholder="请输入登录名"  />
                    </Form.Item>

                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>

                <div style={myStyle1}>
                    <Dropdown overlay={operations}>
                        <Action.Button>
                            <Space>
                                更多操作
                                <DownOutlined />
                            </Space>
                        </Action.Button>
                    </Dropdown>
                </div>

                <div style={myStyle1}></div>
                <div>
                    <Table
                        pagination={false} 
                        rowKey="id" 
                        columns={columns} 
                        dataSource={dataSource}
                        loading={loading}
                        scroll={{ y: 500, x: '70vw' }}
                    >
                    </Table>
                </div>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>
                <Modal
                    title="添加OPENAPI用户"
                    open={visible_add}
                    onCancel={this.onFinishAddCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width="700px"
                >
                    <Form
                        onFinish={this.onFinishAdd}
                        ref={this.formRefAdd}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <Form.Item label="云平台名称" name="platform" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择云平台"
                                onChange={this.onChangePlatform}
                                >
                                {search_option_platform}
                            </Select>
                        </Form.Item>

                        <Form.Item label="云账户名称" name="account_name" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择云账户"
                                >
                                {search_option_account}
                            </Select>
                        </Form.Item>

                        <Form.Item label="登陆名称" name="username" rules={[{ required: true}]}>
                            <Input></Input>
                        </Form.Item>

                        <Form.Item label="备注" name="comments" rules={[{ required: true}]}>
                            <Input></Input>
                        </Form.Item>


                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                <Modal
                    title="删除OPENAPI用户"
                    open={visible_del}
                    onCancel={this.onFinishDelCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width="700px"
                >
                    <Form
                        onFinish={this.onFinishDel}
                        ref={this.formRefDel}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >
                    <Form.Item label="云平台名称" name="platform" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择云平台"
                                onChange={this.onChangePlatform}
                                >
                                {search_option_platform}
                            </Select>
                        </Form.Item>

                        <Form.Item label="云账户名称" name="account_name" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="选择云账户"
                                onChange={this.onChangeAccount}
                                >
                                {search_option_account}
                            </Select>
                        </Form.Item>
                        <Form.Item label="登陆名称" name="username" rules={[{ required: true}]}>
                            <Select
                                    allowClear
                                    showSearch
                                    style={{ width: '100%' }}
                                    placeholder="请选择登陆名"
                                    onChange={this.onChangeAccount}
                                    >
                                    {search_option_username}
                                </Select>                           
                        </Form.Item>

                        <Form.Item label="AK" name="ak" rules={[{ required: false}]}>
                            <Input></Input>
                        </Form.Item>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

            </Fragment>
        )
    }
}
export default CloudRamUser;